

#import "QRSystemVC.h"
#import "Util.h"
#import "SignInViewController.h"
@interface QRSystemVC () <UIWebViewDelegate>
{
    NSTimer *_timer;
    UIImageView *_imageView;

    UIImageView *_lineImageView;
    
    int KScreenWidth;
    int KScreenHeight;
}
@end

@implementation QRSystemVC

//- (void)dealloc
//{
//    [_delegate release];
//    [_device release];
//    [_output release];
//    [_input release];
//    [_session release];
//    [_preview release];
//    [super dealloc];
//}

- (void)viewDidLoad {
    
    
    KScreenWidth = self.view.frame.size.width;
    KScreenHeight = self.view.frame.size.height;
    
    [super viewDidLoad];
    self.view.autoresizingMask = YES;
    
    self.view.backgroundColor = [UIColor grayColor];
    
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
    [self initUiConfig];

    self.view.backgroundColor = [UIColor whiteColor];
    
    //导航栏的返回按钮
    UIButton *leftNavView =[UIButton buttonWithType:UIButtonTypeCustom];
    leftNavView.frame = CGRectMake(0, 0, KScreenWidth/4, 44);
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 13, 10, 18)];
    img.image = [UIImage imageNamed:@"dismiss"];
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
       img.image = [UIImage imageNamed:@"dismissGray"];
    }
    
    [leftNavView addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [leftNavView addSubview:img];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:leftNavView];
    self.navigationItem.leftBarButtonItem= leftItem;
//    [leftItem release];
//    [img release];
    
    self.navigationItem.title = @"扫描";
    
}

- (void)backButtonClick
{
    //设置通知，显示tabbar
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showBootomBar" object:self userInfo:nil ];

    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initUiConfig
{
    //初始化 扫描控件
    [self initUI:CGRectMake(0, 0, self.view.bounds.size.width,self.view.bounds.size.height)];
    
    /**  加载界面想要添加的元素与扫描二维码无关
     */
    
    _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pick_bg"]];
    _imageView.frame = CGRectMake(self.view.bounds.size.width * 0.5 - 140, self.view.bounds.size.height * 0.5 - 140, 280, 280);
    [self.view addSubview:_imageView];
    
    _lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 280, 2)];
    _lineImageView.image = [UIImage imageNamed:@"QRXscanline"];
    [_imageView addSubview:_lineImageView];
    
    UILabel *detailLab = [[UILabel alloc] initWithFrame:CGRectMake(_imageView.frame.origin.x+10, _imageView.frame.size.height+_imageView.frame.origin.y+13, _imageView.frame.size.width-20, 30)];
    detailLab.text = @"将二维码放入框内，即可自动扫描";
    detailLab.textColor = [UIColor whiteColor];
    detailLab.font = [UIFont systemFontOfSize:15.0f];
    [self.view addSubview:detailLab];
    
    //执行动画
    [self animation];
    
    
    //    _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(animation) userInfo:nil repeats:YES];
}


- (void)initUI:(CGRect)previewFrame
{
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    NSError *error = nil;
    
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    
    if (error) {
        
        if ([self.delegate respondsToSelector:@selector(qrCodeError:)]) {
            [self.delegate qrCodeError:error];
        }
        
        NSLog(@"你手机不支持二维码扫描!");
        return;
    }
    
    self.output = [[AVCaptureMetadataOutput alloc]init];
    
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    
    self.session = [[AVCaptureSession alloc]init];
    
    if ([self.session canAddInput:self.input])
    {
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.output])
    {
        [self.session addOutput:self.output];
    }
    
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode];
    // 设置支持编码详见链接 条形码／二维码 http://baike.baidu.com/link?url=OlRd2WD3pT_nD_crHl_FvfiKEKtSm9iSqnqCLQFE5Z2I_9m1rXO-4pVwoLnAwiJcZF--ghRVaUjAhWOEznQ8VK#9
    
    
    /**
     *   AVCaptureVideoPreviewLayer  A CoreAnimation layer subclass for previewing
     *   the visual output of an AVCaptureSession
     *   将捕获器访入Layer中
     */
    self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    //.

    
    /**
     *  相当于 视图的contentMode 
     *  AVLayerVideoGravityResizeAspect 适应 （调整宽高比例，即放大缩小，显示全部）
     *  AVLayerVideoGravityResizeAspectFill 填充 （原比例填满，显示部分）
     *  AVLayerVideoGravityResize 拉伸 （，显示全部）
     */
    self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.preview.frame = previewFrame;
    
    [self.view.layer addSublayer:self.preview];//
    
    /**
     *  详见<AVCaptureSession.h>
     *  //调整 视频 图像质量
     */
    if ([UIScreen mainScreen].bounds.size.height == 480)
    {
        [self.session setSessionPreset:AVCaptureSessionPreset640x480];
    }
    else
    {
        [self.session setSessionPreset:AVCaptureSessionPresetHigh];
        //调整分辨率
    }
    [self.session startRunning];//捕捉起开始运行
}

//捕捉器 捕捉到 制定类型的图案
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    [self.session stopRunning];     //捕捉器停止运行

    NSString *val = nil;
    if (metadataObjects.count > 0)
    {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        
//      AVMetadataMachineReadableCodeObject is a concrete subclass of AVMetadataObject defining the features of a detected one-dimensional or two-dimensional barcode.
//      AVMetadataMachineReadableCodeObject AVMetadataObject的具体子类定义的特性检测一维或二维条形码。
        // 检测一维或二维条形码 的类
        val = obj.stringValue;// 图案内容
//       NSArray *arr = obj.corners;//边界点 （范围：0-1）
        NSLog(@"val---%@",val);

        NSString *urlString=[NSString string];
        if ([val hasPrefix:@"http"]) {
            urlString = val;
        }else if ([val hasPrefix:@"www."]) {
            urlString = [NSString stringWithFormat:@"http:%@",val];
        }
        
        else {
            [self.preview removeFromSuperlayer];    //移除layer
            [_lineImageView removeFromSuperview];
            [_imageView removeFromSuperview];
            
            CGSize size =[self calculateTextHeight:val];
            UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(10, 64, size.width, size.height)];
            label.text = val;
            label.numberOfLines =0;
            [self.view addSubview:label];
//            [label release];
            
//            [CYToast showStatusWithString:@"无法识别的二维码" hideAfterDelay:0.7];
//            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        
        NSString *catid;
        NSString *bid;
        
        NSLog(@"urlString == %@",urlString);
        if ([val hasPrefix:@"http://www.kanshangjie.com/install"]) {
            urlString = val;
            NSArray *array1 = [urlString componentsSeparatedByString:@"&catid="]; //从字符A中分隔成2个元素的数组
            NSString *twoIdString = array1[1];
            NSArray *array2 = [twoIdString componentsSeparatedByString:@"&id="]; //从字符A中分隔成2个元素的数组
            catid = array2[0];
            bid   = array2[1];
            NSLog(@"array1:%@",array1);
            NSLog(@"array2:%@",array2);
            
            [UserDefaults setObject:array2 forKey:@"singInArray"];//刷新在中间
            
            UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            SignInViewController*login=[story instantiateViewControllerWithIdentifier:@"SignInViewController"];
            UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:login];
            [self.navigationController pushViewController:login animated:YES];
            
            [SVProgressHUD dismiss];
        }
        else {
        [SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeClear];
//        [CYToast showStatusWithString:@"加载中..."];
        [self.preview removeFromSuperlayer];    //移除layer
        UIWebView * webView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 64, KScreenWidth, KScreenHeight-64)];
        NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:val]];
        [webView loadRequest:request];
        webView.delegate = self;
            [self.view addSubview:webView];
        }
//        [webView release];
    }
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
    [SVProgressHUD dismiss];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"Webview加载出错:-%@",error);
    [SVProgressHUD dismiss];
    if (error.code == -1001) {
//        [CYToast showErrorWithString:@"请求超时"];
        [SVProgressHUD showWithStatus:@"请求超时" maskType:SVProgressHUDMaskTypeClear];
    }
}

//动画
- (void)animation
{
    NSNumber *fromValue = @10; NSNumber *toValue = @270; NSNumber *endValue = toValue;
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"position.y";
    animation.duration = 3;
    animation.fromValue = fromValue;
    animation.toValue = toValue;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = MAX_INPUT; // 重复次数
    animation.removedOnCompletion = YES;
    animation.autoreverses = YES;
    endValue = toValue;
    _lineImageView.layer.position = CGPointMake(_lineImageView.layer.position.x, [endValue intValue]);
    
    NSString *key = [NSString stringWithFormat:@"ani-move"];
    [_lineImageView.layer addAnimation:animation forKey:key];
    
    
//    [UIView animateWithDuration:2.8 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
//        
//        _lineImageView.frame = CGRectMake(0, 260, 280, 2);
//        
//    } completion:^(BOOL finished) {
//        _lineImageView.frame = CGRectMake(0, 10, 280, 2);
//    }];
}

- (void)cancelBtnClick:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark ------计算文字的高度------
-(CGSize)calculateTextHeight:(NSString*)string {
    CGRect textRect=[string boundingRectWithSize:CGSizeMake(KScreenWidth-20, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    return textRect.size;
}
//
//- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
//{
////    UIInterfaceOrientationUnknown
////    UIInterfaceOrientationPortrait
////    UIInterfaceOrientationPortraitUpsideDown
////    ,
////    UIInterfaceOrientationLandscapeLeft
////    UIInterfaceOrientationLandscapeRight
//    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
//        self.preview.frame = CGRectMake(0, 0, self.view.bounds.size.height, self.view.bounds.size.width);
////        self.preview.affineTransform = CGAffineTransformMakeRotation(M_PI_2);
//    }else
//    {
//        self.preview.affineTransform = CGAffineTransformIdentity;
//    }
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
